//
//  BindingWXVC.m
//  QoilPublic
//
//  Created by SunChao on 17/9/18.
//  Copyright © 2017年 杨凯. All rights reserved.
//

#import "BindingWXVC.h"
#import "QMakeInvoiceCell.h"
@interface BindingWXVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic,strong)UITableView *tbView;
@property (nonatomic,strong)UIButton *agreeBtn;
@property (nonatomic,strong)UILabel *textLabel;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)NSMutableArray *dataDefaultSource;
@property(nonatomic,strong)NSIndexPath *indexPath;
@property (nonatomic,copy)NSString *nameString;
@property (nonatomic,copy)NSString *codeString;
@property (nonatomic,copy)NSMutableArray *cardArr;


@end

@implementation BindingWXVC

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *cardsArr = @[@"微信账号",@"验证码"];
    NSArray *cardDefaultArr = @[@"请输入微信号/手机号",@"请输入验证码"];
    
    self.dataSource = cardsArr.mutableCopy;
    self.dataDefaultSource = cardDefaultArr.mutableCopy;
    NSString *textString = @"请绑定本人微信账号";
    
    UIView *header =[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    
    UILabel *lab =[QViewUtility createLabelWithFrame:CGRectMake(25, 16, kScreenWidth, 20) font:Ksize13 textAlignment:0 textColor:[QColorUtility defaultDeepGrayColor] text:textString];
    [header addSubview:lab];
    
    self.tbView.tableHeaderView =header;
    //提交
    UIView * footer =[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.5)];
    lineLabel.backgroundColor  = [UIColor groupTableViewBackgroundColor];
    [footer addSubview:lineLabel];
    _agreeBtn =[QViewUtility createButtonWithFrame:CGRectMake(40, 35, kScreenWidth - 80, 45) font:Ksize17 title:@"提交" titleColor:[UIColor whiteColor] backgroundColor:[QColorUtility defaultBlueColor]];
    [_agreeBtn addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    _agreeBtn.layer.cornerRadius = 7;
    _agreeBtn.clipsToBounds = YES;
    [footer addSubview:_agreeBtn];
    self.tbView.tableFooterView = footer;
    
    NSString *tipString = @"\"温馨提示\": 只能绑定一种提现账户";
    UILabel *label = [QViewUtility createLabelWithFrame:CGRectMake(25, 95, kScreenWidth-50, 20) font:Ksize13 textAlignment:1 textColor:[QColorUtility defaultRedColor] text:tipString];
    [footer addSubview:label];
    
    [self.view addSubview:self.tbView];
    [self.tbView registerNib:[UINib nibWithNibName:@"QMakeInvoiceCell" bundle:nil] forCellReuseIdentifier:@"QMakeInvoiceCell"];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    
    [self.tbView.backgroundView addGestureRecognizer:tap];
    
}
- (void)tap
{
    [self.view endEditing:YES];
    
}
- (void)submitAction{
    
    [self.view endEditing:YES];
    
    if ([self.nameString isEqualToString:@""]||self.nameString == nil) {
        [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"请输入微信号/手机号" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        return;
    }
    if ([self.codeString isEqualToString:@""]||self.codeString == nil) {
        [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"请输入验证码" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        return;
    }

    
    [self requestData];
}


- (void)requestData{
    
    NSString *name = self.nameString;
    NSString *code = self.codeString;
    NSString *url = [QParamService urlWithAction:@"userinfo/getAdd"];
    NSDictionary *params = [QParamService BindingBankWithName:@"" CardType:@"2" CardNum:name Identity:@"" Ramark:@"微信绑定测试" Code:code];
    [QViewUtility showMBHudToView:self.view hideBg:YES];
    [QViewUtility disMissNoRecordInVC:self];
    [QViewUtility disMissNoNetWorkInVC:self];
    [[QHttpManager sharedManager] POST:url parameterMD5:params completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [_tbView.mj_header endRefreshing];
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            if([QUserInfo sharedInfo].isHaveNetWork == NO){
                [QViewUtility showNoNetWorkInView:_tbView];
            }
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"提交成功" btnTitle:showAlertBtnTitle type:1 myBlock:^{
               
                [self.navigationController popViewControllerAnimated:YES];
                 [[NSNotificationCenter defaultCenter]postNotificationName:@"AddNewCardNotification" object:nil];
            }];
            
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
    
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (UITableView*)tbView {
    if (!_tbView) {
        _tbView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
        _tbView.dataSource = self;
        _tbView.delegate = self;
        _tbView.backgroundColor = [UIColor whiteColor];
        _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tbView.bounces = NO;
    }
    return _tbView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 2;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger row = [indexPath row];
    
    QMakeInvoiceCell * cell= [tableView dequeueReusableCellWithIdentifier:@"QMakeInvoiceCell" forIndexPath:indexPath];
    cell.titleLabe.text =_dataSource[row];
    cell.textField.placeholder  = _dataDefaultSource[row];
    cell.textField.clearButtonMode=UITextFieldViewModeWhileEditing;
    cell.textField.tag = row;
    cell.textField.delegate = self;
    cell.secondLab.hidden = YES;
    cell.thirdLab.hidden = YES;
    cell.codeBtn.hidden = YES;
    
    [cell.textField addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    
    if (indexPath.row == 1) {
        _indexPath = indexPath;
        cell.codeBtn.hidden = NO;
        cell.textField.keyboardType = UIKeyboardTypePhonePad;
        [cell setNewFrameWithTextField];
        cell.codeBlock = ^(UIButton *button){
            [QParamService onTimer:button type:NO];
            [self requestCardCode];
            [self.view endEditing:YES];
        };
    }
    
    return cell;
}
#pragma mark-----请求验证码接口
    - (void)requestCardCode{
        NSString *url = [QParamService urlWithAction:@"getVerificationCode"];
        NSDictionary *param = [QParamService getCardCode];
        [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
            if(error){
                return ;
            }
            QBaseModel *basModel = [QBaseModel objectFromDict:dict];
            if([basModel.result isEqualToString:@"success"]){
                [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"验证码已发送,请注意查收" btnTitle:showAlertBtnTitle type:1 myBlock:^{ }];
            }else{
                [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            }
        }];
    }
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self.tbView endEditing:YES];
}
- (void)textFieldWithText:(UITextField *)textField
{
    if (textField.tag == 0) {
        self.nameString = textField.text;
    }
    if (textField.tag == 1) {
        self.codeString = textField.text;
    }
    
}

#pragma UITextFieldDelegate实现输入四位数出现一个空格
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    
    NSString *text = [textField text];
    if ([string isEqualToString:@""]) {
        return YES;
    }
    if (text.length>=19) {
        [self.view endEditing:YES];
//        [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"超出输入限制" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        return NO;
    }
    if (textField.tag == 1) {
        if (text.length >=6) {
            [self.view endEditing:YES];
            return NO;
        }
    }
    
    
    return YES;
}


@end
